import React, { useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { RootState } from '../../store';
import { Card, Form, Input, Select, Button, message, Upload, Modal } from 'antd';
import Header from '../../components/Header/Header';
import ImgCrop from 'antd-img-crop';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { updateUserinfo, getUserInfo, getAdminUserInfo } from '../../api/userController';
import {setLoginUser} from "../../store/loginUser.tsx";

const { Option } = Select;

const EditProfile: React.FC = () => {
    const dispatch = useDispatch();
    const loginUser = useSelector((state: RootState) => state.loginUser);
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>(loginUser.avatarUrl || '');

    React.useEffect(() => {
        console.log(loginUser);
        form.setFieldsValue({
            nickName: loginUser.nickName,
            gender: loginUser.gender,
            phone: loginUser.phone,
            wxCode: loginUser.wxcode,
            userProfile: loginUser.userProfile,
            address: loginUser.address
        });
    }, [loginUser, form]);

    const onFinish = async (values: any) => {
        try {
            const updateData = {
                nickName: values.nickName,
                gender: values.gender,
                phone: values.phone,
                wxCode: values.wxCode,
                userProfile: values.userProfile,
                avatarUrl: imageUrl
            };
            
            const response = await updateUserinfo(updateData);
            if (response.code === 200) {
                message.success('个人信息更新成功！');
                const result = await getAdminUserInfo();
                if (result.code === 200) {
                    dispatch(setLoginUser(result.data));
                }
            } else {
                message.error(response.message || '更新失败，请重试！');
            }
        } catch (error) {
            message.error('更新失败，请重试！');
        }
    };

    const beforeUpload = (file: RcFile) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('只能上传 JPG/PNG 格式的图片!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('图片大小不能超过 2MB!');
        }
        return isJpgOrPng && isLt2M;
    };

    const handleChange: UploadProps['onChange'] = (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            if (info.file.response.code === 200) {
                setLoading(false);
                const newAvatarUrl = info.file.response.data;
                setImageUrl(newAvatarUrl);
                getUserInfo().then(result => {
                    if (result.code === 200) {
                        dispatch({
                            type: 'SET_LOGIN_USER',
                            payload: result.data
                        });
                    }
                });
                message.success('头像上传成功！');
            } else {
                setLoading(false);
                message.error(info.file.response.message || '头像上传失败！');
            }
        } else if (info.file.status === 'error') {
            setLoading(false);
            message.error('头像上传失败，请重试！');
        }
    };

    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>上传头像</div>
        </div>
    );

    return (
        <div className="min-h-screen bg-gray-50">
            <Header />
            
            <div className="container mx-auto px-4 py-8">
                <div className="max-w-[1400px] mx-auto">
                    <Card 
                        title="编辑个人资料" 
                        className="shadow-sm"
                        headStyle={{ borderBottom: '1px solid #f0f0f0' }}
                    >
                        <Form
                            form={form}
                            layout="vertical"
                            initialValues={{
                                nickName: loginUser.nickName,
                                gender: loginUser.gender,
                                phone: loginUser.phone,
                                wxCode: loginUser.wxCode,
                                userProfile: loginUser.userProfile,
                                avatarUrl: loginUser.avatarUrl,
                                address: loginUser.address
                            }}
                            onFinish={onFinish}
                            className="max-w-[800px] mx-auto"
                        >
                            <Form.Item label="头像" className="mb-8">
                                <ImgCrop rotationSlider>
                                    <Upload
                                        name="file"
                                        listType="picture-card"
                                        className="avatar-uploader"
                                        showUploadList={false}
                                        action="http://localhost:8081/api/file/upload"
                                        beforeUpload={beforeUpload}
                                        onChange={handleChange}
                                        data={{
                                            biz: 'user_avatar'
                                        }}
                                        withCredentials={true}
                                    >
                                        {imageUrl ? (
                                            <img 
                                                src={imageUrl} 
                                                alt="avatar" 
                                                style={{ width: '100%', height: '100%', objectFit: 'cover' }} 
                                            />
                                        ) : (
                                            uploadButton
                                        )}
                                    </Upload>
                                </ImgCrop>
                            </Form.Item>

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-x-6">
                                <Form.Item
                                    label="昵称"
                                    name="nickName"
                                    rules={[{ required: true, message: '请输入昵称' }]}
                                >
                                    <Input placeholder="请输入昵称" />
                                </Form.Item>

                                <Form.Item
                                    label="性别"
                                    name="gender"
                                >
                                    <Select placeholder="请选择性别">
                                        <Option value={0}>男</Option>
                                        <Option value={1}>女</Option>
                                    </Select>
                                </Form.Item>

                                <Form.Item
                                    label="手机号码"
                                    name="phone"
                                >
                                    <Input placeholder="请输入手机号码" />
                                </Form.Item>

                                <Form.Item
                                    label="微信"
                                    name="wxCode"
                                >
                                    <Input placeholder="请输入微信号" />
                                </Form.Item>
                            </div>

                            <Form.Item
                                label="个人简介"
                                name="userProfile"
                                className="col-span-full"
                            >
                                <Input.TextArea 
                                    placeholder="请输入个人简介" 
                                    rows={3}
                                />
                            </Form.Item>

                            <Form.Item
                                label="地址"
                                name="address"
                                className="col-span-full"
                            >
                                <Input.TextArea 
                                    placeholder="请输入地址" 
                                    rows={3}
                                    disabled
                                    className="bg-gray-50"
                                />
                            </Form.Item>

                            <Form.Item className="flex justify-center mt-6">
                                <Button 
                                    type="primary" 
                                    htmlType="submit"
                                    className="mr-4"
                                >
                                    保存修改
                                </Button>
                                <Button 
                                    onClick={() => window.history.back()}
                                >
                                    取消
                                </Button>
                            </Form.Item>
                        </Form>
                    </Card>
                </div>
            </div>
        </div>
    );
};

export default EditProfile; 